package com.example.demo.service.impl;

import com.example.demo.mapper.ImageMapper;
import com.example.demo.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ImageServiceImpl implements ImageService {
    @Autowired
    private ImageMapper imageMapper;

    @Override
    public void saveImagePath(List<String> imagePath) {
        if (imagePath != null && !imagePath.isEmpty()) {
            // 先检查哪些图片路径已经存在
            List<String> existingPaths = imageMapper.checkImagePathExists(imagePath);

            // 过滤出不存在的图片路径
            List<String> newPaths = imagePath.stream()
                    .filter(path -> !existingPaths.contains(path))
                    .collect(Collectors.toList());

            // 只插入不存在的图片路径
            if (!newPaths.isEmpty()) {
                imageMapper.saveImagePath(newPaths);
            }
        }
    }

    @Override
    public String getRandomImage() {
        String imagePath = imageMapper.getRandomAvailableImage();
        if (imagePath != null) {
            // 将图片状态更新为已使用（disable=0）
            imageMapper.updateImageStatus(imagePath, 0);
        }
        return imagePath;
    }
}
